package com.olive.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.olive.dto.ResultInfo;
import com.olive.dto.UserDto;
import com.olive.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author huangjinjin ( 22080514 )
 * @Date 2023/2/9 12:55
 * @Version 1.0
 */
@Component
public class CustomSuccentHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        ResultInfo<Map<String, Object>> result = new ResultInfo<>();
        if( authentication instanceof UsernamePasswordAuthenticationToken){
            Map<String, Object> map = new HashMap<>();
            UserDto userDto = (UserDto)authentication.getPrincipal();
            String jwtToken = jwtTokenUtil.generateToken(userDto);
            map.put("userInfo", userDto);
            map.put("token", jwtToken);
            result.setCode(200);
            result.setMsg("success");
            result.setData(map);
        }else{
            result.setCode(501);
            result.setMsg("error");
        }
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter pw = httpServletResponse.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        pw.write(mapper.writeValueAsString(result));
        pw.flush();
    }
}
